//
//  SelectListViewController.m
//  Etion
//
//  Created by  user on 11-2-8.
//  Copyright 2011 GuangZhouXuanWu. All rights reserved.
//

#import "XUIPickerPanelView.h"

#import "NSDateExtend.h"

#import "XUIPanelWindow.h"

#define DATETAG    20
#define TIMERTAG 21

@interface XUIPickerPanelView ()<UIPickerViewDelegate, UIPickerViewDataSource, UIGestureRecognizerDelegate>
{
    XUIPickerPanelViewType _pickerPanelType;
    __unsafe_unretained id <XUIPickerPanelViewDataSource> _dataSource;
    __unsafe_unretained id <XUIPickerPanelViewDelegate> _delegate;
    UIPickerView *_pickerView;
    UIDatePicker *_datePicker;
    UIToolbar *_toolBar;
    
    BOOL _hiddenToolBar;
    
    UILabel *_titleLabel;
    
    XUIPanelWindow *_window;
}
@end

@implementation XUIPickerPanelView

@synthesize dataSource = _dataSource;
@synthesize delegate = _delegate;
@synthesize hiddenToolBar = _hiddenToolBar;
@synthesize pickerPanelType = _pickerPanelType;

/*
- (id)initWithPickerPanelType:(XUIPickerPanelViewType)type
{
    self = [super init];

    _hiddenToolBar = NO;

    _pickerPanelType = type;

    return self;
}

#ifdef ETIONIPAD
- (void)resetPickerViewSize:(CGSize)size
{
    CGFloat height = 0.0;
    if(m_toolbar != nil)
    {
        m_toolbar.frame = CGRectMake(0, 0, size.width, m_toolbar.frame.size.height);
        height += m_toolbar.frame.size.height;
    }
    if(_pickerView != nil)
    {
        _pickerView.frame = CGRectMake(0, m_toolbar.frame.size.height, size.width, size.height);
        height += _pickerView.frame.size.height;
    }
    if(_datePicker != nil)
    {
        _datePicker.frame = CGRectMake(0, m_toolbar.frame.size.height, size.width, size.height);
        height += _datePicker.frame.size.height;
    }
    self.view.frame = CGRectMake(0, 0, size.width, height);
}
#endif

- (void)loadView
{
    self.view = [[[UIView alloc] initWithFrame:CGRectZero] autorelease_mm];
    
#ifndef ETIONIPAD
    self.view.frame = _window.bounds;
#endif
    
    self.view.backgroundColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.6];
}
 */

- (id)initWithPickerPanelType:(XUIPickerPanelViewType)type
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    
    self.backgroundColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.6];
    
    _hiddenToolBar = NO;
    
    _pickerPanelType = type;
    
    return self;
}

- (void)willMoveToWindow:(UIWindow *)newWindow
{
    [super willMoveToWindow:newWindow];
    
    if(newWindow == nil)
        return;
    
    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)]
                                   autorelease_mm];
    tap.delegate = self;
    [self addGestureRecognizer:tap];

    
    CGFloat y = 0.0;
    
    self.layer.opacity = 0;
    y = self.height;

    _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,/*self.view.frame.origin.y+*/y, self.width, 44)];
    [_toolBar setBackgroundImage:[UIImage imageNamed:@"ppvcl_toolbarbg.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    [self addSubview:_toolBar];

    CGFloat h = _toolBar.frame.size.height;
#ifndef ETIONIPAD
    h = 0.0;
#endif
    CGRect frame = CGRectMake(0,y + h, self.width, 216);

    UIBarButtonItem *item1 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(close)] autorelease_mm];
    UIBarButtonItem *item2 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease_mm];
    UIBarButtonItem *item3 = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)] autorelease_mm];

    [_toolBar setItems:@[item1,item2,item3] animated:YES];
    
    if(_titleLabel != nil && _pickerPanelType != XUIPickerPanelViewTypeDateTime)
    {
        _titleLabel.centerX = _toolBar.width /2;
        _titleLabel.centerY = _toolBar.height /2;
        [_toolBar addSubview:_titleLabel];
    }
    
    switch (_pickerPanelType)
    {
        case XUIPickerPanelViewTypeComBoBox:
        {
            _pickerView = [[UIPickerView alloc] initWithFrame:frame];
            _pickerView.dataSource = self;
            _pickerView.delegate = self;
            _pickerView.showsSelectionIndicator = YES;
            _pickerView.backgroundColor=[UIColor whiteColor];
            [_pickerView selectRow:[_dataSource defaultRowInPickerPanelViewController:self] inComponent:0 animated:YES];
            [self addSubview:_pickerView];
            break;
        }
        case XUIPickerPanelViewTypeDate:
        {
            _datePicker = [[UIDatePicker alloc] initWithFrame:frame];
            _datePicker.timeZone = [NSTimeZone defaultTimeZone];
            _datePicker.datePickerMode = UIDatePickerModeDate;
            _datePicker.date = [_dataSource currentDateInPickerPanelView:self];

            NSDate* mindate=nil;
            NSDate* maxdate=nil;
            if([_dataSource respondsToSelector:@selector(minDateInPickerPanelView:)]==YES)
                mindate=[_dataSource minDateInPickerPanelView:self];
            else
                mindate=[NSDate formatNSStringDate:@"1901-01-01 00:00:00" format:@"yyyy-MM-dd HH:mm:ss"];
            if([_dataSource respondsToSelector:@selector(maxDateInPickerPanelView:)]==YES)
                maxdate=[_dataSource maxDateInPickerPanelView:self];
            else
                maxdate=[NSDate formatNSStringDate:@"2099-12-31 23:59:59" format:@"yyyy-MM-dd HH:mm:ss"];

            _datePicker.minimumDate = mindate;
            _datePicker.maximumDate = maxdate;

            _datePicker.backgroundColor=[UIColor whiteColor];
            [self addSubview:_datePicker];
            break;
        }
        case XUIPickerPanelViewTypeTime:
        {
            _datePicker = [[UIDatePicker alloc] initWithFrame:frame];
            _datePicker.timeZone = [NSTimeZone defaultTimeZone];
            _datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
            _datePicker.date = [_dataSource currentDateInPickerPanelView:self];

            NSDate* mindate=nil;
            NSDate* maxdate=nil;
            if([_dataSource respondsToSelector:@selector(minDateInPickerPanelView:)]==YES)
                mindate=[_dataSource minDateInPickerPanelView:self];
            else
                mindate=[NSDate formatNSStringDate:@"1901-01-01 00:00:00" format:@"yyyy-MM-dd HH:mm:ss"];
            if([_dataSource respondsToSelector:@selector(maxDateInPickerPanelView:)]==YES)
                maxdate=[_dataSource maxDateInPickerPanelView:self];
            else
                maxdate=[NSDate formatNSStringDate:@"2099-12-31 23:59:59" format:@"yyyy-MM-dd HH:mm:ss"];

            _datePicker.minimumDate = mindate;
            _datePicker.maximumDate = maxdate;

            _datePicker.backgroundColor=[UIColor whiteColor];
            [self addSubview:_datePicker];
            break;
        }
        case XUIPickerPanelViewTypeDateTime:
        {
            _datePicker = [[UIDatePicker alloc] initWithFrame:frame];
            _datePicker.timeZone = [NSTimeZone defaultTimeZone];
            _datePicker.datePickerMode = UIDatePickerModeDate;
            _datePicker.date = [_dataSource currentDateInPickerPanelView:self];

            NSDate* mindate=nil;
            NSDate* maxdate=nil;
            if([_dataSource respondsToSelector:@selector(minDateInPickerPanelView:)]==YES)
                mindate=[_dataSource minDateInPickerPanelView:self];
            else
                mindate=[NSDate formatNSStringDate:@"1901-01-01 00:00:00" format:@"yyyy-MM-dd HH:mm:ss"];
            if([_dataSource respondsToSelector:@selector(maxDateInPickerPanelView:)]==YES)
                maxdate=[_dataSource maxDateInPickerPanelView:self];
            else
                maxdate=[NSDate formatNSStringDate:@"2099-12-31 23:59:59" format:@"yyyy-MM-dd HH:mm:ss"];

            _datePicker.minimumDate = mindate;
            _datePicker.maximumDate = maxdate;
            
            _datePicker.backgroundColor=[UIColor whiteColor];
            [self addSubview:_datePicker];
            
            UISegmentedControl *seg = [[[UISegmentedControl alloc]initWithItems:@[@"日期",@"时间"]] autorelease_mm];
            seg.frame = CGRectMake(0, 0, 120, 30);
            seg.center = CGPointMake(_toolBar.width/2, _toolBar.height/2);
            [seg addTarget:self action:@selector(segmentedControlClick:) forControlEvents:UIControlEventValueChanged];
            [_toolBar addSubview:seg];
            seg.selectedSegmentIndex  = 0;
            
            break;
        }
    }
}

-(void)setToolBarTitle:(NSString *)toolBarTitle
{
    if(_titleLabel == nil)
    {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 180, 40)];
        _titleLabel.font = [UIFont systemFontOfSize:16];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        if(_toolBar != nil)
        {
            _titleLabel.centerX = _toolBar.width /2;
            _titleLabel.centerY = _toolBar.height /2;
            [_toolBar addSubview:_titleLabel];
        }
    }
    _titleLabel.text = toolBarTitle;
}

- (void)pickerViewReloadAllRow
{
    [_pickerView reloadAllComponents];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSUInteger nCount = [_dataSource numberOfRowInPickerPanelView:self];
    if (nCount <= 0)
        pickerView.userInteractionEnabled = NO;
    else
        pickerView.userInteractionEnabled = YES;
    return nCount;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_dataSource pickerPanelView:self titleForRow:row forComponent:component];
}

- (void)repositionPickerpanel:(CGFloat)nHeight
{
    CGFloat h = nHeight;
    if (nil != _pickerView)
    {
        CGRect frame = _pickerView.frame;
        frame.origin.y += h;
        _pickerView.frame = frame;
    }
    if (nil != _datePicker)
    {
        CGRect frame = _datePicker.frame;
        frame.origin.y += h;
        _datePicker.frame = frame;
    }
}

- (void)show
{
#ifndef ETIONIPAD
    [self _show];
#else
    [self resetPickerViewSize:CGSizeMake(320, 216)];
#endif
}

- (void)_show
{
    _window = [XUIPanelWindow new];
    _window.responder = self;
    
    CGFloat nHeight = -216;

    [UIView animateWithDuration:0.3 animations:^
    {
        CGRect frame = _toolBar.frame;
        frame.origin.y += (nHeight + (_toolBar.height * (ABS(nHeight)/ nHeight) * !_hiddenToolBar));
        _toolBar.frame = frame;
        
        [self repositionPickerpanel:nHeight];
        
        self.layer.opacity = 1;
        
    }];
}

- (void)_closeWithWillDoneSelector:(SEL)willDoneSelector doneSelector:(SEL)doneSelector
{
    CGFloat nHeight = 216;
    
    if([_delegate respondsToSelector:willDoneSelector])
        [_delegate performSelector:willDoneSelector withObject:self];
    [UIView animateWithDuration:0.3 animations:^
    {
        CGRect frame = _toolBar.frame;
        frame.origin.y += (nHeight + (_toolBar.frame.size.height * (ABS(nHeight)/ nHeight) * !_hiddenToolBar));
        _toolBar.frame = frame;
        
        [self repositionPickerpanel:216];
        
        self.layer.opacity = 0;
    } completion:^(BOOL finished)
    {
        if([_delegate respondsToSelector:doneSelector])
           [_delegate performSelector:doneSelector withObject:self];
    //    [_rootVcl dismissViewControllerAnimated:NO completion:NO];
        ReleaseObj(_window);
    }];
}

//- (void)SetPickerViewCurrentSelectRow
//{
//    [_dataSource pickerPanelView:self selectedRowAtIndex:[_pickerView selectedRowInComponent:0]];
//}

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)gr
{
    [self close];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint p = [touch locationInView:self];
    CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - CGRectGetHeight(_toolBar.frame) - 216);
    if (CGRectContainsPoint(frame, p) == YES)
        return YES;
    return NO;
}

- (void)close
{
//	[self ExitAnimated:@selector(pickerPanelViewDidCancel:)];

#ifndef ETIONIPAD
    [self _closeWithWillDoneSelector:@selector(pickerPanelViewWillCancel:) doneSelector:@selector(pickerPanelViewDidCancel:)];
#else
    [m_target performSelector:@selector(pickerPanelViewDidFinish:)];
#endif
}

- (void)done
{
    switch (_pickerPanelType)
    {
        case XUIPickerPanelViewTypeComBoBox:
        {
            if (_pickerView != nil)
                [_dataSource pickerPanelView:self selectedRowAtIndex:[_pickerView selectedRowInComponent:0]];
            break;
        }
        case XUIPickerPanelViewTypeDate:
        case XUIPickerPanelViewTypeTime:
        case XUIPickerPanelViewTypeDateTime:
        {
            [_dataSource pickerPanelView:self selectedDate:_datePicker.date];
            break;
        }
    }

#ifndef ETIONIPAD
    [self _closeWithWillDoneSelector:@selector(pickerPanelViewWillFinish:) doneSelector:@selector(pickerPanelViewDidFinish:)];
#else
    [m_target performSelector:@selector(pickerPanelViewDidFinish:)];
#endif
}

-(void)segmentedControlClick:(UISegmentedControl*)sender
{
    NSDate *date = _datePicker.date;
    NSUInteger index = sender.selectedSegmentIndex;
    if (index == 0)
    {
        _datePicker.datePickerMode = UIDatePickerModeDate;
    } else if (index == 1)
    {
        _datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
    }

    [_datePicker setDate:date animated:NO];
}

- (void)dealloc
{
    [_window release_mm];
    [_toolBar release_mm];
    [_pickerView release_mm];
    [_datePicker release_mm];
    superdealloc_mm;
}


@end
